package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理中心
 * 所有的异常都可以到这里进行进一步的处理
 * @author panda
 * @since 2022/12/28 3:31
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody//json返回数据
@Slf4j
public class globalExceptionHandle {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String exMessage = ex.getMessage();
        log.error(exMessage);
        //如果包含信息内容为"Duplicate entry"的信息,则将其处理一下
        if (exMessage.contains("Duplicate entry")) {
            String[] split = exMessage.split(" ");
            String massage = split[2] + "已经存在";
            return R.error(massage);
        }
        return R.error("存在未知异常");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> CategoryExceptionHandler(CustomException ce) {
        log.error(ce.getMessage());
        return R.error(ce.getMessage());
    }


}